package com.tuanbiao.presenter.auth;

import com.hzjq.data.minbao.entity.AuthEntity;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.controllers.AuthController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.transformers.SchedulerTransformer;
import com.tuanbiao.utils.TxtUtils;

import java.io.File;
import java.util.Collections;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * @author abiao
 * @since 2022/4/25 11:21
 */
public class AuthLocalPresenter extends BasePresenter<AuthController.Model, AuthController.LocalView> implements AuthController.LocalPresenter {
    public AuthLocalPresenter(AuthController.Model model, AuthController.LocalView rootView) {
        super(model, rootView);
    }

    @Override
    public void refresh() {
        addDispose(Observable.create((ObservableOnSubscribe<List<File>>) emitter -> {
                    List<File> files = TxtUtils.getAllTxt();
                    Collections.sort(files, (o1, o2) -> {
                        if (o1.lastModified() > o2.lastModified()) {
                            return -1;
                        } else if (o1.lastModified() == o2.lastModified()) {
                            return 0;
                        } else {
                            return 1;
                        }
                    });
                    emitter.onNext(files);
                }).compose(new SchedulerTransformer<>())
                .subscribe(files -> mRootView.setItems(files)));
    }

    @Override
    public void getAuthFile(File file, String password) {
        mModel.parseAuthFile(file, password, new OnBaseResultCallback<AuthEntity>() {
            @Override
            public void onSuccess(AuthEntity entity) {
                mRootView.showMessage("提取成功");
            }

            @Override
            public void onFailed(String msg) {
                mRootView.showMessage(msg);
            }
        });
    }
}
